package jwt0

import (
	"gitee.com/sdynasty/clever/errors"
	"github.com/dgrijalva/jwt-go"
)


type Credentials struct {
	//UserId   string
	ServerNo string
	Secret   string //密文
}

type JWTUtil struct {
	Cred     Credentials
	claims   *Claims
	TokenStr string
}


//创建签名串
func (j *JWTUtil) CreateSignedString() (signedString string, err error) {
	//token超时时间
	//expirTime := time.Now().Add(30 * time.Minute)
	claims := &Claims{
		//UserId:         j.Cred.UserId,
		ServerNo:       j.Cred.ServerNo,
		StandardClaims: jwt.StandardClaims{
			//ExpiresAt: expirTime.Unix(),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	//创建jwt 签名串
	return token.SignedString([]byte(j.Cred.Secret))
}

//解析签名串
func (j *JWTUtil) ParseSignedString() (*Claims, error) {
	j.claims = &Claims{}
	//解析JWT string
	tkn, err := jwt.ParseWithClaims(j.TokenStr, j.claims, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(j.Cred.Secret), err
	})

	if err != nil {
		if err == jwt.ErrSignatureInvalid {
			return nil, errors.New("signature invalid")
		}
		return nil, err
	}

	if !tkn.Valid {
		return nil, errors.New("token invalid")
	}
	return j.claims, nil

}

